<template>
    <div class="demand-detail">
        <a-modal width="1300px" :visible="visible" title="编辑需求" @cancel="closeModal" class="yuan-modal demand-detail-modal"
            :dialog-style="{ top: '20px' }">
            <a-spin tip="Loading..." :spinning="saveLoading">
                <a-form-model layout="inline" class="yuan-form" ref="form" :model="formData" :rules="rules"
                    :label-col="{ style: { width: '150px' } }" :wrapper-col="{ style: { width: 'calc(100% - 160px)' } }">
                    <div class="form-panel">

                        <div class="form-panel-box">
                            <div v-show="!isNext || isShow">
                                <a-form-model-item label="封面图" class="yuan-form-item" v-if="pageReady">
                                    <UploadVue :uploadLength="1" @uploadChange="uploadChangeCoverImageUrl"
                                        :defImgList="formData.coverPicture?[formData.coverPicture]:[]" />
                                    <div style="line-height:30px">jpg.png.gif格式.不超过2MB</div>
                                </a-form-model-item>
                                <div class="form-title">
                                    成果类型
                                </div>
                                <a-form-model-item class="yuan-form-row" label="">
                                    <a-radio-group v-model="formData.demandType">
                                        <a-radio value="本人成果">本人成果</a-radio>
                                        <a-radio value="委托方成果">委托方成果</a-radio>
                                    </a-radio-group>
                                </a-form-model-item>
                                <template v-if="formData.demandType==='委托方成果'">
                                    <div class="form-title">
                                        委托人信息
                                    </div>
                                    <a-form-model-item class="yuan-form-item yuan-form-col5" label="委托人企业/单位名称"
                                        prop="smallProNum">
                                        <a-input class="yuan-form-input" v-model="formData.clientCompanyName"
                                            placeholder="请输入委托人企业/单位名称"></a-input>
                                    </a-form-model-item>
                                    <a-form-model-item class="yuan-form-item yuan-form-col5" label="委托人姓名" prop="smallProNum">
                                        <a-input class="yuan-form-input" v-model="formData.clientName"
                                            placeholder="请输入委托人姓名"></a-input>
                                    </a-form-model-item>
                                    <a-form-model-item class="yuan-form-item yuan-form-col5" label="委托人联系方式" prop="smallProNum">
                                        <a-input class="yuan-form-input" v-model="formData.clientContact"
                                            placeholder="请输入委托人联系方式"></a-input>
                                    </a-form-model-item>
                                </template>
                                <div class="form-title">
                                    成果基本信息
                                </div>
                                <a-form-model-item class="yuan-form-item yuan-form-col5" label="成果名称" prop="achievementName">
                                    <a-input class="yuan-form-input" v-model="formData.achievementName"
                                        placeholder="成果名称"></a-input>
                                </a-form-model-item>
                                <a-form-model-item class="yuan-form-item yuan-form-col5" label="成果负责人"
                                    prop="achievementPrincipal">
                                    <a-input class="yuan-form-input" v-model="formData.achievementPrincipal"
                                        placeholder="成果负责人"></a-input>
                                </a-form-model-item>
                                <!-- <a-form-model-item class="yuan-form-item yuan-form-col5" label="联系方式"
                                    prop="achievementPrincipalPhone">
                                    <a-input class="yuan-form-input" v-model="formData.achievementPrincipalPhone"
                                        placeholder="联系方式"></a-input>
                                </a-form-model-item> -->
                                <a-form-model-item class="yuan-form-row" label="成果类别" prop="achievementCategory">
                                    <a-radio-group v-model="formData.achievementCategory">
                                        <a-radio value="发明专利">发明专利</a-radio>
                                        <a-radio value="实用新型专利">实用新型专利</a-radio>
                                        <a-radio value="外观设计专利">外观设计专利</a-radio>
                                        <a-radio value="技术">技术</a-radio>
                                        <a-radio value="软件著作权">软件著作权</a-radio>
                                        <a-radio value="版权等其他著作权">版权等其他著作权</a-radio>
                                        <a-radio value="集成电路布图设计">集成电路布图设计</a-radio>
                                        <a-radio value="植物新品种">植物新品种</a-radio>
                                        <a-radio value="其他">
                                            <span>其他：</span>
                                            <CountInputVue style="margin-left:5px" class="yuan-form-input"
                                                v-model="formData.achievementCategoryOther" :maxNum="15" placeholder="请输入" />
                                        </a-radio>
                                    </a-radio-group>
                                </a-form-model-item>

                                <a-form-model-item class="yuan-form-row" label="所属技术类别" prop="belongToTechnologyCategory">
                                    <a-checkbox-group v-model="formData.belongToTechnologyCategory">
                                        <a-checkbox :value="item.content" v-for="item in territoryList"
                                            :key="item.id">{{item.content}}</a-checkbox>
                                        <a-checkbox value="其他">
                                            <span>其他：</span>
                                            <CountInputVue style="margin-left:5px" class="yuan-form-input"
                                                v-model="formData.belongToTechnologyCategoryOther" :maxNum="15"
                                                placeholder="请输入" />
                                        </a-checkbox>
                                    </a-checkbox-group>
                                </a-form-model-item>

                                <a-form-model-item class="yuan-form-row" label="推广形式" prop="promotionForm">
                                    <a-checkbox-group v-model="formData.promotionForm">
                                        <a-checkbox :value="item.content" v-for="item in promotionFormList"
                                            :key="item.id">{{item.content}}</a-checkbox>
                                        <a-checkbox value="其他">
                                            <span>其他：</span>
                                            <CountInputVue style="margin-left:5px" class="yuan-form-input"
                                                v-model="formData.promotionFormOther" :maxNum="15" placeholder="请输入" />
                                        </a-checkbox>
                                    </a-checkbox-group>
                                </a-form-model-item>

                                <a-form-model-item class="yuan-form-row" label="研究形式" prop="studyForm">
                                    <a-radio-group v-model="formData.studyForm">
                                        <a-radio value="独立研究">独立研究</a-radio>
                                        <a-radio value="与院校合作">与院校合作</a-radio>
                                        <a-radio value="与企业合作">与企业合作</a-radio>
                                        <a-radio value="与国（境）外合作">与国（境）外合作</a-radio>
                                        <a-radio value="其他">
                                            <span>其他：</span>
                                            <CountInputVue style="margin-left:5px" class="yuan-form-input"
                                                v-model="formData.studyFormOther" :maxNum="15" placeholder="请输入" />
                                        </a-radio>
                                    </a-radio-group>
                                </a-form-model-item>
                                <a-form-model-item class="yuan-form-row" label="成果体现形式" prop="embodyForm">
                                    <a-checkbox-group v-model="formData.embodyForm">
                                        <a-checkbox value="新技术">新技术</a-checkbox>
                                        <a-checkbox value="新产品">新产品</a-checkbox>
                                        <a-checkbox value="新工艺">新工艺</a-checkbox>
                                        <a-checkbox value="农业，生物新品种">农业，生物新品种</a-checkbox>
                                        <a-checkbox value="新材料">新材料</a-checkbox>
                                        <a-checkbox value="新装备">新装备</a-checkbox>
                                        <a-checkbox value="行业标准">行业标准</a-checkbox>
                                        <a-checkbox value="国家标准">国家标准</a-checkbox>
                                        <a-checkbox value="地方标准">地方标准</a-checkbox>
                                        <a-checkbox value="企业标准">企业标准</a-checkbox>
                                        <a-checkbox value="国际标准">国际标准</a-checkbox>
                                        <a-checkbox value="矿产新品种">矿产新品种</a-checkbox>
                                        <a-checkbox value="其他">
                                            <span>其他应用技术:</span>
                                            <CountInputVue style="margin-left:5px" class="yuan-form-input"
                                                v-model="formData.embodyFormOther" :maxNum="15" placeholder="请输入" />
                                        </a-checkbox>
                                    </a-checkbox-group>
                                </a-form-model-item>
                                <a-form-model-item class="yuan-form-row" label="应用行业" prop="applicationIndustry">
                                    <a-checkbox-group v-model="formData.applicationIndustry">
                                        <a-checkbox :value="item.content" v-for="item in applicationIndustryList"
                                            :key="item.id">{{item.content}}</a-checkbox>
                                        <a-checkbox value="其他">
                                            <span>其他应用技术:</span>
                                            <CountInputVue style="margin-left:5px" class="yuan-form-input"
                                                v-model="formData.applicationIndustryOther" :maxNum="15" placeholder="请输入" />
                                        </a-checkbox>
                                    </a-checkbox-group>
                                </a-form-model-item>
                                <a-form-model-item class="yuan-form-row" label="技术成熟度" prop="skillRipe">
                                    <a-radio-group v-model="formData.skillRipe">
                                        <a-radio value="成熟应用阶段">成熟应用阶段</a-radio>
                                        <a-radio value="中期阶段">中期阶段</a-radio>
                                        <a-radio value="初期阶段">初期阶段</a-radio>
                                    </a-radio-group>
                                </a-form-model-item>
                                <a-form-model-item class="yuan-form-item yuan-form-col5" label="联系人" prop="contacts">
                                    <a-input class="yuan-form-input" v-model="formData.contacts" placeholder="请输入联系人"></a-input>
                                </a-form-model-item>
                                <a-form-model-item class="yuan-form-item yuan-form-col5" label="联系方式" prop="contactWay">
                                    <a-input class="yuan-form-input" v-model="formData.contactWay"
                                        placeholder="请输入联系方式"></a-input>
                                </a-form-model-item>
                                <a-form-model-item class="yuan-form-row" label="成果简介" prop="achievementDescription">
                                    <a-input type="textarea" style="width: 500px;background-color:#F7F7F7" :rows="5"
                                        v-model="formData.achievementDescription" placeholder="请输入" :maxLength="1000" />
                                </a-form-model-item>
                            </div>
                            <div v-show="isNext || isShow">
                                <div class="form-title">
                                    其他信息
                                </div>
                                <a-form-model-item class="yuan-form-row" label="关键词">
                                    <div v-for="(item,idx) in formData.keyword" :key="'keyword_'+idx">
                                        <a-input class="yuan-form-input" v-model="formData.keyword[idx]"
                                            placeholder="请输入关键词"></a-input>
                                        <a-button type="danger" style="margin-left:10px" @click="delKeyword(idx)">移除</a-button>
                                    </div>
                                    <a-button type="primary" @click="addKeyword">添加关键词</a-button>
                                </a-form-model-item>
                                <a-form-model-item class="yuan-form-row" label="课题来源" prop="taskSource">
                                    <a-radio-group v-model="formData.taskSource">
                                        <a-radio :value="item.content" v-for="item in taskSourceList"
                                            :key="item.id">{{item.content}}</a-radio>
                                        <a-radio value="其他">
                                            <span>其他：</span>
                                            <CountInputVue style="margin-left:5px" class="yuan-form-input"
                                                v-model="formData.taskSourceOther" :maxNum="15" placeholder="请输入" />
                                        </a-radio>
                                    </a-radio-group>
                                </a-form-model-item>
                                <a-form-model-item class="yuan-form-row" label="应用状态" prop="useState">
                                    <a-radio-group v-model="formData.useState">
                                        <a-radio value="产业化应用">产业化应用</a-radio>
                                        <a-radio value="小批量或小范围应用">小批量或小范围应用</a-radio>
                                        <a-radio value="试用">试用</a-radio>
                                        <a-radio value="未应用">未应用</a-radio>
                                        <a-radio value="应用后停用">应用后停用</a-radio>
                                    </a-radio-group>
                                </a-form-model-item>
                                <a-form-model-item class="yuan-form-item yuan-form-col5" label="成果年份" prop="achievementYearPage">
                                    <a-date-picker mode="year" class="yuan-form-input" placeholder="选择年份"
                                        v-model="formData.achievementYearPage" inputReadOnly format="YYYY" :open="monthPickShow"
                                        @panelChange="handlePanelChange" @openChange="handleOpenChange" />
                                </a-form-model-item>
                                <a-form-model-item class="yuan-form-item yuan-form-col5" label="发布地址" prop="placeAreaCode">
                                    <a-cascader class="yuan-form-input" v-model="formData.placeAreaCode" :options="addrData"
                                        placeholder="请选择" @change="onAddrChange" />
                                </a-form-model-item>

                                <a-form-model-item class="yuan-form-row" label="其他" prop="otherDetails">
                                    <a-input type="textarea" style="width: 500px;background-color:#F7F7F7" :rows="5"
                                        v-model="formData.otherDetails" placeholder="请输入" :maxLength="1000" />
                                </a-form-model-item>

                                <a-form-model-item label="介绍图片" class="yuan-form-item" v-if="pageReady">
                                    <UploadVue :uploadLength="3" @uploadChange="uploadChangeIntroImageUrl"
                                        :defImgList="formData.introducePicture?formData.introducePicture:[]" />
                                    <div style="line-height:30px">jpg.png.gif格式.不超过2MB</div>
                                </a-form-model-item>
                                <a-form-model-item class="yuan-form-item" label="介绍视频" prop="introduceVideo">
                                    <a-input class="yuan-form-input" style="max-width:500px" v-model="formData.introduceVideo"
                                        placeholder="请输入视频地址"></a-input>
                                </a-form-model-item>

                                <a-form-model-item class="yuan-form-row" label="授权经纪人">
                                    <div v-for="(item,idx) in formData.brokerRelevances">
                                        <span style="display:inline-block;width:200px;;border-bottom: solid 1px #eee;">{{item.technicalRepresentative}}</span>
                                        <a-button type="danger" @click="delUser(idx)" v-if="!isShow">移除</a-button>
                                    </div>
                                    <div></div>
                                    <a-button type="primary" @click="()=>userVisible=true" v-if="!isShow">选择技术经纪人</a-button>
                                </a-form-model-item>

                                <a-form-model-item class="yuan-form-row" label="成果描述" prop="synopsis">
                                    <div class="editor" style="min-height:300px;width:1000px">
                                        <Toolbar style="border-bottom: 1px solid #ccc;" :editor="editorRef"
                                            :defaultConfig="editorConfig.toolbarConfig" mode="default" />
                                        <Editor v-model="formData.synopsis" :defaultConfig="editorConfig" mode="default"
                                            @onCreated="handleCreated" />
                                    </div>
                                </a-form-model-item>
                            </div>
                        </div>

                    </div>
                </a-form-model>
            </a-spin>
            <template slot="footer">

                <template v-if="isShow">
                    <a-button type="primary" @click="closeModal">
                        关闭
                    </a-button>
                </template>
                <template v-else>
                    <a-button @click="isNext=true" type="warning" :loading="saveLoading" v-if="!isNext">
                        下一步
                    </a-button>
                    <a-button @click="isNext=false" type="warning" :loading="saveLoading" v-else>
                        上一步
                    </a-button>

                    <a-button @click="modalOk" type="primary" :loading="saveLoading" v-if="isNext">
                        确认保存
                    </a-button>
                    <a-button @click="closeModal">
                        取消
                    </a-button>
                </template>
            </template>

            <UserVue :visible="userVisible" @closeModal="() => userVisible = false" @sureClose="selectUser" />
        </a-modal>
    </div>
</template>

<script lang="ts">
import { Component, Prop, Watch, Vue } from "vue-property-decorator";
import UploadVue from "@/components/upload.vue";
import UserVue from "@/components/addUserModal.vue";
import areaJson, { getAreaWords } from "@/utils/area";
import api from "@/api/api";
import { format } from "@/utils";
import CountInputVue from "@/components/countInput.vue";

import { MENU_CONF, toolbarConfig } from "@/utils/wangeditors";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";

@Component({
    name: "tpl",
    components: { UploadVue, UserVue, CountInputVue, Editor, Toolbar },
})
export default class extends Vue {
    @Prop({ default: false }) visible!: boolean;
    @Prop({ default: false }) isShow!: boolean;
    @Prop({ default: "" }) editId!: string;

    @Watch("visible")
    visibleChange() {
        if (this.visible) {
            if (this.editId) {
                this.getDetailInfo();
            } else {
                this.formData = { brokerRelevances: [], keyword:[] };
                this.pageReady = true;
            }
        } else {
            this.pageReady = false;
        }
    }
    isNext = false;
    editorRef = null;
    editorConfig = {
        placeholder: "请输入内容...",
        //配置工具栏
        toolbarConfig: toolbarConfig,
        MENU_CONF: MENU_CONF,
    };
    saveLoading = false;
    formData: any = {
        brokerRelevances: [],
        keyword:[]
    };
    rules = {
        achievementName: [{ required: true, message: "请输入成果名称", trigger: "change" }],
        achievementPrincipal: [{ required: true, message: "请输入成果负责人", trigger: "change" }],
        achievementPrincipalPhone: [{ required: true, message: "请输入成果负责人联系方式", trigger: "change" }],
        achievementCategory: [{ required: true, message: "请选择成果类别", trigger: "change" }],
        // taskSource: [{ required: true, message: "请选择课题来源", trigger: "change" }],
        belongToTechnologyCategory: [{ required: true, message: "请选择所属技术类别", trigger: "change" }],
        // useState: [{ required: true, message: "请选择应用状态", trigger: "change" }],
        promotionForm: [{ required: true, message: "请选择推广形式", trigger: "change" }],
        studyForm: [{ required: true, message: "请选择研究形式", trigger: "change" }],
        // achievementYearPage: [{ required: true, message: "请输入成果年份", trigger: "change" }],
        embodyForm: [{ required: true, message: "请选择成果体现形式", trigger: "change" }],
        applicationIndustry: [{ required: true, message: "请选择应用行业", trigger: "change" }],
        skillRipe: [{ required: true, message: "请选择技术成熟度", trigger: "change" }],
        contacts: [{ required: true, message: "请填写联系人", trigger: "change" }],
        contactWay: [{ required: true, message: "请填写联系方式", trigger: "change" }],
        achievementDescription: [{ required: true, message: "请填写成果简介", trigger: "change" }],
        synopsis: [{ required: true, message: "请填写成果描述", trigger: "change" }],
        // placeAreaCode: [{ required: true, message: "请选择发布地址", trigger: "change" }],
    };
    pageReady = false;
    userVisible = false;

    async mounted() {
        this.setAddrData();
        this.getTerritoryList();
        this.getTaskSourceList();
        this.getPromotionFormList();
        this.getApplicationIndustryList();
    }
    closeModal() {
        this.$emit("closeModal");
    }
    otherArr = [
        "achievementCategory",
        "taskSource",
        "belongToTechnologyCategory",
        "promotionForm",
        "studyForm",
        "embodyForm",
        "applicationIndustry",
    ];
    async getDetailInfo() {
        this.saveLoading = true;
        try {
            const res = await api.getAchList({ id: this.editId });
            res.data.introducePicture = res.data.introducePicture ? JSON.parse(res.data.introducePicture) : [];
            res.data.demandType = res.data.achievementDifferentiate || "本人成果";
            res.data.placeAreaCode = res.data.code ? res.data.code.split(",") : [];
            if (res.data.achievementYear) {
                res.data.achievementYearPage = format(new Date(res.data.achievementYear + "/01/01"));
            }
            res.data.synopsis=res.data.synopsis||''
            this.otherArr.forEach((item) => {
                if (typeof res.data[item] === "string") {
                    if (res.data[item].indexOf("其他-") >= 0) {
                        const val = res.data[item].split("-");
                        res.data[item] = "其他";
                        res.data[item + "Other"] = val[1];
                    }
                } else if (typeof res.data[item] === "object" && res.data[item]) {
                    res.data[item] = res.data[item].map((child) => {
                        if (child.indexOf("其他-") >= 0) {
                            const val = child.split("-");
                            res.data[item + "Other"] = val[1];
                            return "其他";
                        } else {
                            return child;
                        }
                    });
                }
            });
            this.formData = res.data;
            this.pageReady = true;
        } finally {
            this.saveLoading = false;
        }
    }
    async modalOk() {
        if (!this.formData.demandType) {
            this.$message.error("请选择成果类型");
            return;
        }
        (this.$refs.form as any).validate(async (valid: boolean) => {
            if (!valid) {
                this.$message.error("必填信息不完整，请检查后重试");
                return;
            }
            this.saveLoading = true;
            try {
                const data = {
                    ...this.formData,
                    coverPicture:this.formData.coverPicture?this.formData.coverPicture:'https://zyykjcgzhxt.cdutcm.edu.cn/picture/moren.png',
                    ifDeliver: 0,
                    sign:'后台',
                    achievementDifferentiate: this.formData.demandType,
                };
                this.otherArr.forEach((item) => {
                    if (typeof data[item] === "string") {
                        if (data[item] === "其他") {
                            data[item] = "其他-" + (data[item + "Other"] || '');
                        }
                    } else if (typeof data[item] === "object" && data[item]) {
                        data[item] = data[item].map((child) => {
                            if (child === "其他") {
                                return "其他-" +  (data[item + "Other"] || '');
                            } else {
                                return child;
                            }
                        });
                    }
                });
                const res = await api.addAch(data);
                this.$message.success("保存成功");
                this.closeModal();
                this.$emit("resetList");
            } finally {
                this.saveLoading = false;
            }
        });
    }
    uploadChangeHead(e) {
        this.formData.headPortrait = e.length ? e[0].url : "";
    }
    uploadChangeCoverImageUrl(e) {
        this.formData.coverPicture = e.length ? e[0].url : "";
    }
    uploadChangeIntroImageUrl(e) {
        this.formData.introducePicture = e.map((item) => item.url);
    }
    addrData: any[] = [];
    setAddrData() {
        this.addrData = areaJson;
    }

    territoryList = [];
    async getTerritoryList() {
        try {
            this.saveLoading = true;
            const res = await api.getSetting("3");
            this.territoryList = res.data;
        } finally {
            this.saveLoading = false;
        }
    }
    taskSourceList = [];
    async getTaskSourceList() {
        try {
            this.saveLoading = true;
            const res = await api.getSetting("2");
            this.taskSourceList = res.data;
        } finally {
            this.saveLoading = false;
        }
    }
    promotionFormList = [];
    async getPromotionFormList() {
        try {
            this.saveLoading = true;
            const res = await api.getSetting("4");
            this.promotionFormList = res.data;
        } finally {
            this.saveLoading = false;
        }
    }
    applicationIndustryList = [];
    async getApplicationIndustryList() {
        try {
            this.saveLoading = true;
            const res = await api.getSetting("5");
            this.applicationIndustryList = res.data;
        } finally {
            this.saveLoading = false;
        }
    }

    deadlineChange() {
        const nowTime = new Date().getTime();
        const deadlineTime = new Date(this.formData.deadline).getTime();
        const day = (deadlineTime - nowTime) / (24 * 60 * 60 * 1000);
        this.formData.deadlineDay = Math.ceil(day);
    }
    onAddrChange(e: any) {
        this.formData.code = e.join(",");
        this.formData.location = getAreaWords(e);
    }

    selectUser(userInfo) {
        if (this.formData.brokerRelevances) {
            this.formData.brokerRelevances.push({
                technicalRepresentative: userInfo.name,
                technicalHeadPortrait: userInfo.headPortrait,
                technicalPhone: userInfo.phone,
            });
        } else {
            this.formData.brokerRelevances = [
                {
                    technicalRepresentative: userInfo.name,
                    technicalHeadPortrait: userInfo.headPortrait,
                    technicalPhone: userInfo.phone,
                },
            ];
        }
    }

    delUser(idx) {
        this.formData.brokerRelevances.splice(idx, 1);
    }

    monthPickShow = false;
    handlePanelChange(value) {
        this.formData.achievementYear = value.format("YYYY");
        this.formData.achievementYearPage = value.format("YYYY");
        this.monthPickShow = false;
    }
    handleOpenChange(status) {
        if (status) {
            this.monthPickShow = true;
        } else {
            this.monthPickShow = false;
        }
    }

    handleCreated(editor) {
        this.editorRef = editor; // 记录 editor 实例
    }

    delKeyword(idx) {
        this.formData.keyword.splice(idx, 1);
    }
    addKeyword() {
        this.formData.keyword.push("");
    }
}
</script>
<style lang="scss">
.demand-detail-modal {
    .form-title {
        font-size: 16px;
        color: #204fb6;
        padding: 10px 0;
        border-bottom: solid 1px #eee;
        display: flex;
        align-items: center;
        margin-bottom: 5px;
    }
    .form-title::before {
        content: "";
        display: inline-block;
        height: 15px;
        width: 3px;
        background-color: #204fb6;
        margin-right: 8px;
    }
    .yuan-form-row {
        margin-bottom: 20px;
        
        .ant-checkbox-wrapper,.ant-radio-wrapper{
            line-height: 40px;
        }
    }
}
</style>
